package com.yu.controller;

import static org.junit.Assert.fail;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.ResourceBundle.Control;
import java.util.Timer;
import java.util.TimerTask;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.junit.runners.Parameterized.Parameters;
import org.omg.PortableInterceptor.USER_EXCEPTION;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.w3c.dom.UserDataHandler;

import com.sun.mail.handlers.message_rfc822;
import com.yu.bean.Msg;
import com.yu.bean.Tpicture;
import com.yu.bean.User;
import com.yu.service.UserService;
import com.yu.utils.CodeUtil;
import com.yu.utils.MailUtil;
import com.yu.utils.VerifiCode;

/**
 * @author YUjiangpeng
 *(注意：千万不要写空的@RequestMaping(),否则会导致加载不了静态自资源)
 */
@Controller
public class UerController {
	
	@Autowired UserService userService;
	
	
	/**
	 * 仅仅用作跳转
	 * 跳向注册页面
	 * @return
	 */
	@RequestMapping("/mregisterLink")
	public String  megisterLink(){
		return "mregister";
	}
	
	/**
	 * 仅仅用作跳转
	 * 跳向注册页面
	 * @return
	 */
	@RequestMapping("/pregisterLink")
	public String  registerLink(){
		return "pregister";
	}
	
	/**
	 * 仅仅用作跳转
	 * @return
	 */
	@RequestMapping("/loginLink")
	public String  loginLink(){
		return "ulogin";
	}
	
	
	/**
	 * 登录倒计时跳转页面
	 * @return
	 */
	@RequestMapping("/stimerLink")
	public String stimer(){
		return "stimer";
		
	}
	/**
	 * 登录倒计时跳转页面
	 * @return
	 */
	@RequestMapping("/ftimerLink")
	public String ftimer(){
		return "ftimer";
		
	}
	
	
	/**
	 * 注册成功倒计时页面
	 * @return
	 */
	@RequestMapping("/rtimerLink")
	public String rtimer(){
		return "rtimer";
		
	}
	
	/**
	 * 验证用户登录验证用户名和密码 或者手机号和密码
	 * @return
	 */
	@RequestMapping(value="/userLogin", method=RequestMethod.GET)
	@ResponseBody
	public Msg userLogin(@RequestParam(value="userName",required=true)String userName , 
			@RequestParam(value="pwd", required=true)String pwd, HttpSession session){
		User u = (User)userService.getUserByNameAndPwd(userName, pwd);
		if (u != null) {
			session.setAttribute("u", u);
			System.out.println("用户的签名为"+u.getSigniture());
			return Msg.success().add("msg", "登录成功正在跳转中!");
		}else{
			return Msg.fail().add("err", "登录失败请检查用户名!");
		}
		
		
	} 
	
	@RequestMapping("/verifiCode")
	public void verificationCode(HttpServletRequest request, HttpServletResponse response) throws IOException{
		 /*
        1.生成验证码
        2.把验证码上的文本存在session中
        3.把验证码图片发送给客户端
        */
		
		 //设置浏览器不要缓存此图片
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expirse", 0);
		response.setContentType("image/jpeg");
       VerifiCode v=new VerifiCode();     //用我们的验证码类，生成验证码类对象
       BufferedImage image=v.getImage();  //获取验证码
       request.getSession().setAttribute("vcode", v.getText()); //将验证码的文本存在session中
       VerifiCode.output(image, response.getOutputStream());//将验证码图片响应给客户端
	}
	
	
	/**
	 * 检查邮箱格式，并检验是否被注册
	 * @return
	 */
	@RequestMapping(value="/checkMail", method=RequestMethod.POST)
	@ResponseBody
	public Msg checkMail( String email){
		 String regx = "^([a-z0-9_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})$";
		 if (!email.matches(regx)) {
				return Msg.fail().add("regx", "邮箱格式错误！");
			}else if (!userService.checkMail(email)) {
				return Msg.fail().add("regx", "邮箱已经被注册！");
			}else{
			return Msg.success().add("regx", "");	
		
		}
		
	}
	
	/**
	 * 获取邮箱注册码
	 * @param email
	 * @return
	 */
	@RequestMapping(value="/getVerifiCode",method=RequestMethod.POST)
	@ResponseBody
	public Msg getVerifiCode(String email, HttpSession session){
		 String regx = "^([a-z0-9_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})$";
		 if (!email.matches(regx)) {
				return Msg.fail().add("regx", "邮箱格式错误！");
			}else if (!userService.checkMail(email)) {
				return Msg.fail().add("regx", "邮箱已经被注册！");
			}else{
				//获取注册码
				String code = String.valueOf(CodeUtil.gennerateRandomCode());
				session.setAttribute("codeN", code);
				new Thread(new MailUtil(email, code)).start();
				Timer t = new Timer();
				t.schedule(new TimerTask() {
					
					@Override
					public void run() {
						// TODO Auto-generated method stub
						if(session.getAttribute("codeN")!=null){
						//long l = System.currentTimeMillis()-session.getLastAccessedTime();
						session.removeAttribute("codeN");
						System.out.println("销毁验证码！！！！！！");
						}
					}
				},60000 , 120000); //延迟60秒后执行，每间隔2分钟执行一次
				return Msg.success().add("regx", "");		
		}
		
	}
	
	
	/**
	 * 检验用户输入的验证码是否正确
	 * @return
	 */
	@RequestMapping(value="/checkCode", method=RequestMethod.POST)
	@ResponseBody
	public Msg checkCode(@RequestParam("inCode")String code, HttpSession session){
		System.out.println("用户输入的验证码是"+ code);
		String codeN = (String)session.getAttribute("codeN");
		System.out.println("session codeN为"+codeN);
		if (codeN==null||codeN.equals("")) {
			return Msg.fail().add("regx", "请先获取验证码,或验证码已过期！");
		}else if(codeN.equals(code)){
			return Msg.success().add("regx", "");
		}else{
			return Msg.fail().add("regx", "验证码输入错误！");
		}
		
	}
	
	
	/**
	 * 检查用户名格式，检查用户名昵称是否可用，即是否存在
	 * @return
	 */
	@RequestMapping(value="/checkUname", method=RequestMethod.POST)
	@ResponseBody
	public Msg checkUname(String userName){
		 String regx = "^(?!_)(?!.*?_$)([a-zA-Z0-9_\\u4e00-\\u9fa5]{4,10}|[a-zA-Z0-9_]{1,2}[\\u4e00-\\u9fa5]{1,2}|[\\u4e00-\\u9fa5]{1,2}[a-zA-Z0-9_]{1,2}|[\\u4e00-\\u9fa5]{2,10}|[a-zA-Z0-9_]{4,20})$";
		 if (!userName.matches(regx)) {
				return Msg.fail().add("regx", "昵称不能以下划线开头或结尾，2-10个汉字或汉字和字母，或者4-20个英文字母！");
			}else if (!userService.checkUname(userName)) {
				return Msg.fail().add("regx", "该昵称已经存在！");
			}else{
			return Msg.success().add("regx", "");	
		}
	}
	
	/**
	 * 用户注册
	 * @return
	 * bingdingResult 只适合验证所有字段
	 */
	@RequestMapping(value="/uRegister", method=RequestMethod.POST)
	@ResponseBody
	public Msg userRegister(@Valid User user , BindingResult result){
		System.out.println("用户输入的数据为"+user.getUserId()+user.getUserName()+user.getPwd()+user.getEmail());
		if(result.hasErrors()){
			Map<String, Object> map = new HashMap<>();
			//校验失败，应该返回失败，在页面显示错误信息
			List<FieldError> errors = result.getFieldErrors();
			for (FieldError fieldError : errors) {
				System.out.println("错误的字段名："+fieldError.getField());
				System.out.println("错误信息："+fieldError.getDefaultMessage());
				map.put(fieldError.getField(), fieldError.getDefaultMessage());
			}
			return Msg.fail().add("errorFields", map);
					
		}else{
			if(!userService.checkMail(user.getEmail())){
				Map<String, Object> map = new HashMap<>();
				map.put("email", "邮箱已经存在！！！！");
				return Msg.fail().add("errorFields", map);
			}else if(!userService.checkUname(user.getUserName())){
				Map<String, Object> map = new HashMap<>();
				map.put("userName", "用户名已经被注册！！！！");
				return Msg.fail().add("errorFields", map);
			}
			else{
				userService.saveUser(user);
				return Msg.success();	
			}
			
		}
		
	}
	
	
	/**
	 * 登录时判断用对应的用户名是否存在
	 * @param userName
	 * @return
	 */
	@RequestMapping(value="/checkUMP", method=RequestMethod.POST)
	@ResponseBody
	public Msg checkUMP(@RequestParam("userName") String userName){
		System.out.println("输入的账号为"+userName);
	 Boolean b	= userService.checkUMP(userName);
	 if(b){
		return Msg.success().add("regx", "");
	 }
	 else{
		 return Msg.fail().add("regx", "用户名不存在！");
	 }
		
	}
	
	/**
	 * 检验用户登录时输入的验证码是否正确
	 * @return
	 */
	@RequestMapping(value="/checkVcode", method=RequestMethod.POST)
	@ResponseBody
	//一旦使用了@RequestParam("") 则前后端的参数要一模一样 等同于 request.getpPrameters("")
	public Msg checkVcode(@RequestParam("code")String code, HttpSession session){
		System.out.println("yonghushurude结果为"+code);
		String vcode = (String)session.getAttribute("vcode");
		if (code.equals(null)||code == "") {
			return Msg.fail().add("regx", "请输入验证码！");
		}else if(code.equalsIgnoreCase(vcode)){
		     session.removeAttribute("vcode");
			return Msg.success().add("regx", "");
		}else{
			return Msg.fail().add("regx", "验证码输入错误！");
		}
		
	}
	
	
	/**
	 * 退出登录
	 * @return
	 */
	@RequestMapping(value="/logout", method=RequestMethod.POST)
	@ResponseBody
	public Msg getUserName(HttpSession session) {
		session.removeAttribute("u");
		return Msg.success();
		}
	
	
	/**
	 * 判断用户是否登录
	 * @param session
	 * @return
	 */
	@RequestMapping(value="/checkIsLogin", method=RequestMethod.POST)
	@ResponseBody
	public Msg checkIsLogin(HttpSession session){
		User u = (User)session.getAttribute("u"); 
		if(u == null){
			return Msg.fail();
		}else{
			return Msg.success();
		}
		
		
	}
	
	
	/**
	 * 跳转到用户资料设置页面
	 * @return
	 */
	@RequestMapping(value = "/uSettingLink", method=RequestMethod.GET)
	public String uSettingLink(){
		return "userSetting";
	}
	
	
	/**
	 * 
	 * 上传用户头像
	 * @return
	 */
	@RequestMapping(value="/uploadUserImg", method=RequestMethod.POST)
	@ResponseBody
	public Msg uploadUserImg(HttpServletRequest request, MultipartFile file,User user){
		System.out.println("file wei"+file+"用户id 为"+ user.getUserId());
		File targetFile=null;
        String storUrl="";//返回存储路径
        // User u = null;
        System.out.println("开始上传标题图片=========>"+file);
        if(file!= null && !file.equals("") ){
        		String fileName=file.getOriginalFilename();//获取文件名加后缀 
	            String returnUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() +"/upload/imgs/";//存储路径
	            String path = request.getSession().getServletContext().getRealPath("upload/imgs"); //文件存储位置
	            String fileF = fileName.substring(fileName.lastIndexOf("."), fileName.length());//文件后缀
	            fileName=new Date().getTime()+"_"+new Random().nextInt(1000)+fileF;//新的文件名
	            
	            //
	            File file1 =new File(path); 
	            System.out.println("标题图片的上传路径为====>："+path);
	            //如果文件夹不存在则创建    
	            if(!file1 .exists()  && !file1 .isDirectory()){       
	                file1 .mkdir();  
	            }
	            targetFile = new File(file1, fileName);
                //targetFile = new File(path, fileName);
	            try {
	                file.transferTo(targetFile);
                   //msg = returnUrl + fileName;
	               // msg=returnUrl+fileAdd+"/"+fileName;
	                storUrl=returnUrl+fileName;
	                System.out.println("标题图片的返回路径为====》"+storUrl);
	                userService.uploadUpic(user,storUrl);
	                //tpic = tpictureService.selectTpicByUrl(storUrl);
	                System.out.println("上传成功====>"+storUrl);
	            } catch (Exception e) {
	                e.printStackTrace();
	            }
        }
        return Msg.success().add("tpic", 0);
		
	}
	

}
